//
//  LoginController.swift
//  flowerpot
//
//  Created by fyname on 15/9/18.
//  Copyright © 2015年 senhe. All rights reserved.
//

import UIKit
import Starscream
import SwiftyJSON
import CryptoSwift

class LoginController: UIViewController,WebSocketDelegate{
    

    @IBOutlet weak var userName: UITextField!
    
    @IBOutlet weak var passWord: UITextField!
    

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "登录"
        SingletonLoginSocket.sharedInstance.webSocket.delegate = self
        
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    @IBAction func QQLogin(sender: AnyObject) {
        
        if(!UMSocialAccountManager.isOauthAndTokenNotExpired(UMShareToQQ)){
            //qq登录
            let qqPlatform: UMSocialSnsPlatform = UMSocialSnsPlatformManager.getSocialPlatformWithName(UMShareToQQ)
            
            qqPlatform.loginClickHandler(self, UMSocialControllerService.defaultControllerService(), true, {response in
                
                if response.responseCode == UMSResponseCodeSuccess {
                    
                    //登陆成功获取用户信息
                    let snsAccount:UMSocialAccountEntity = UMSocialAccountManager.socialAccountDictionary()[UMShareToQQ] as! UMSocialAccountEntity
                    
                    print("username is \(snsAccount.userName), uid is \(snsAccount.usid), token is \(snsAccount.accessToken) url is \(snsAccount.iconURL)")
                }
            })
            
            //获取accestoken以及新浪用户信息，得到的数据在回调Block对象形参respone的data属性
            UMSocialDataService.defaultDataService().requestSnsInformation(UMShareToQQ) { (response) -> Void in
                print(response.data)
            }
        }
        
    }
    @IBAction func WeiBoLogin(sender: AnyObject) {
        
        //是否已经登陆
        if(!UMSocialAccountManager.isOauthAndTokenNotExpired(UMShareToSina)){
            
            //新浪微博登录
            let snsPlatform: UMSocialSnsPlatform = UMSocialSnsPlatformManager.getSocialPlatformWithName(UMShareToSina)
            
            snsPlatform.loginClickHandler(self, UMSocialControllerService.defaultControllerService(), true, {response in
                
                if response.responseCode == UMSResponseCodeSuccess {
                    
                    //登陆成功获取用户信息
                    let snsAccount:UMSocialAccountEntity = UMSocialAccountManager.socialAccountDictionary()[UMShareToSina] as! UMSocialAccountEntity
                    
                    print("username is \(snsAccount.userName), uid is \(snsAccount.usid), token is \(snsAccount.accessToken) url is \(snsAccount.iconURL)")
                }
            })
            
            //获取accestoken以及新浪用户信息，得到的数据在回调Block对象形参respone的data属性
            UMSocialDataService.defaultDataService().requestSnsInformation(UMShareToSina) { (response) -> Void in
                print(response.data)
            }
        }
        

    }
    @IBAction func WeiXinLogin(sender: AnyObject) {
        
        //是否已经登陆
        if(!UMSocialAccountManager.isOauthAndTokenNotExpired(UMShareToWechatSession)){
            
            //微信登录
            let snsPlatform: UMSocialSnsPlatform = UMSocialSnsPlatformManager.getSocialPlatformWithName(UMShareToWechatSession)
            
            snsPlatform.loginClickHandler(self, UMSocialControllerService.defaultControllerService(), true, {response in
                
                if response.responseCode == UMSResponseCodeSuccess {
                    
                    //登陆成功获取用户信息
                    let snsAccount:UMSocialAccountEntity = UMSocialAccountManager.socialAccountDictionary()[UMShareToWechatSession] as! UMSocialAccountEntity
                    
                    print("username is \(snsAccount.userName), uid is \(snsAccount.usid), token is \(snsAccount.accessToken) url is \(snsAccount.iconURL)")
                }
            })
            
            //获取accestoken以及新浪用户信息，得到的数据在回调Block对象形参respone的data属性
            UMSocialDataService.defaultDataService().requestSnsInformation(UMShareToWechatSession) { (response) -> Void in
                print(response.data)
            }
        }
        
    }
    @IBAction func login(sender: AnyObject) {
        
        CozyLoadingActivity.show("登陆中...", disableUI: true)

        let username = userName.text!
        let password = passWord.text!
        
        if(username == "" || password == ""){

            CozyLoadingActivity.hide(success: false, animated: true)
            print("用户名或密码不能为空!")
        }else{
            
            let up = "\(username):\(password)"
            log.debug(up)
            SingletonLoginSocket.sharedInstance.webSocket.writeString(up)
            //Common.login(username, password: password,callback: loginCallback )
        }
        
    }
    
    private func loginCallback(isOK: Bool){
        if (isOK) {
            
            NSUserDefaults.standardUserDefaults().setObject(self.userName.text!, forKey: "username")
            NSUserDefaults.standardUserDefaults().setObject(self.passWord.text!, forKey: "password")
            
            log.debug("login is ok: \(self.userName)")
            Common.rootViewController.mainTabBarController.view.addSubview(Common.indexVC.view)
            Common.rootViewController.mainTabBarController.view.bringSubviewToFront(Common.rootViewController.mainTabBarController.tabBar)
            Common.rootViewController.showHome()
            
            //统计用户
            MobClick.profileSignInWithPUID(self.userName.text!)
            CozyLoadingActivity.hide(success: true, animated: true)
        }else{
            CozyLoadingActivity.hide(success: false, animated: true)
            print("密码错误!")
        }
    }


    func websocketDidConnect(socket: WebSocket){
        print("已经连接服务器")
        
        
    }
    
    func websocketDidDisconnect(socket: WebSocket, error: NSError?){
        print("连接服务器断开")
    }
    
    func websocketDidReceiveMessage(socket: WebSocket, text: String){
        print("服务器返回数据:\(text)")
        
        let json = JSON(data: text.dataUsingEncoding(NSUTF8StringEncoding)!)
        
        print("json:\(json)")
        
        if(json["msgCode"].stringValue == "666666"){
            
            let pwd = self.passWord.text!
            
            print(pwd)
            
            let dpwd = pwd.dataUsingEncoding(NSUTF8StringEncoding)
            let encrypted: NSData = try! dpwd!.encrypt(AES(key: Common.key, iv: Common.iv))
            
            
            let base64Encoded = encrypted.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
            print("Encoded:  \(base64Encoded)")
            
            
            NSUserDefaults.standardUserDefaults().setObject(self.userName.text!, forKey: "username")
            NSUserDefaults.standardUserDefaults().setObject(base64Encoded, forKey: "password")
            NSUserDefaults.standardUserDefaults().setObject(json["result"]["bmw_id"].stringValue, forKey: "userId")
            NSUserDefaults.standardUserDefaults().setObject(json["result"]["bmw_name"].stringValue, forKey: "userName")
            
            Common.rootViewController.mainTabBarController.view.addSubview(Common.indexVC.view)
            Common.rootViewController.mainTabBarController.view.bringSubviewToFront(Common.rootViewController.mainTabBarController.tabBar)
            Common.rootViewController.showHome()
            
            //统计用户
            MobClick.profileSignInWithPUID(self.userName.text!)
            CozyLoadingActivity.hide(success: true, animated: true)
        }else{
            CozyLoadingActivity.hide(success: false, animated: true)
            print("密码错误!")
        }

    }
    func websocketDidReceiveData(socket: WebSocket, data: NSData){
        
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
